package org.ysh.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.ysh.core.utils.StringUtils;

import static org.ysh.core.utils.Md5Utils.md5;

//@RestController
@Controller
@RequestMapping("/ApiTest")
public class ApiTestController extends BaseController {

    private static final Log log = LogFactory.getLog(ApiTestController.class);

    /**
     * 档案系统部署的http根路径
     */
    private static final String DARJ_PATH = "http://101.35.199.138:7013/prod-api/system";

    /**
     * 本系统访问http根路径
     */
    private static final String ME_PATH = "http://101.35.199.138:7008";

    private static final String PROP_PATH = "ApiTest.properties";
    private static final String SUCCESS = "success";
    private static final String MESSAGE = "message";
    private static final String DATA = "data";
    private static final Map<String, String> map = new LinkedHashMap<>();


    @Resource
    private RestTemplate restTemplate;

    @ResponseBody
    @GetMapping("/hello")
    public String helloWorld() {
        return "hello world";
    }
    /**
     * 等待档案系统下发调用 来获取授权token
     *
     * @param code
     * @param map
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/getAppCode")
    public String getAppCode(String code, ModelMap map) throws IOException {

        boolean suc = false;
        String msg = "接收下发授权失败";

        PathResource pr = new PathResource(new ClassPathResource(PROP_PATH).getURI());
        Properties propertie = PropertiesLoaderUtils.loadProperties(pr);
        String appId = propertie.getProperty("appId");
        String appSecret = propertie.getProperty("appSecret");

        String state = System.currentTimeMillis() + "";

        Map jsonMap = restTemplate.getForObject(DARJ_PATH + "/api/oauth/companyToken?appId=" + appId + "&appSecret=" + appSecret + "&code=" + code + "&redirectUri=" + ME_PATH + "/ApiTest/getAppCode&state=" + state, Map.class);

        if (MapUtils.getBooleanValue(jsonMap, SUCCESS)) {

            Map data = (Map) MapUtils.getObject(jsonMap, DATA);
            if (state.equals(MapUtils.getString(data, "state"))) {

                long expiresIn = MapUtils.getLongValue(data, "expiresIn") * 1000;

                propertie.setProperty("tokenDeathTime", System.currentTimeMillis() + expiresIn + "");
                propertie.setProperty("companyToken", MapUtils.getString(data, "companyToken"));
                propertie.setProperty("refreshToken", MapUtils.getString(data, "refreshToken"));
                propertie.setProperty("companyId", MapUtils.getString(data, "companyId"));

                propertie.store(pr.getOutputStream(), "获取档案系统授权成功" + new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").format(new Date()));

                suc = true;
                msg = "获取档案系统授权成功";
            }
        }

        if (!suc) {
            log.error("从档案系统获取授权失败：jsonMap=" + jsonMap);
        }

        map.put(SUCCESS, suc);
        map.put(MESSAGE, msg);

        return JSON.toJSONString(map);

    }

    /**
     * 定时任务刷新授权
     *
     * @throws IOException
     */
    @Scheduled(cron = "0 0 5 * * ? ")
    public void companyRefresh() throws IOException {
        PathResource pr = new PathResource(new ClassPathResource(PROP_PATH).getURI());
        Properties propertie = PropertiesLoaderUtils.loadProperties(pr);

        String tokenDeathTimeStr = propertie.getProperty("tokenDeathTime");
        if (StringUtils.isNotBlank(tokenDeathTimeStr)) {
            long tokenDeathTime = Long.valueOf(tokenDeathTimeStr);
            long now = System.currentTimeMillis();
            if (now + 259200000 > tokenDeathTime) {// 还有3天就过期了

                String appId = propertie.getProperty("appId");
                String appSecret = propertie.getProperty("appSecret");
                String refreshToken = propertie.getProperty("refreshToken");

                Map jsonMap = restTemplate.getForObject(DARJ_PATH + "/api/oauth/refreshToken?appId=" + appId + "&appSecret=" + appSecret + "&refreshToken=" + refreshToken, Map.class);

                if (MapUtils.getBooleanValue(jsonMap, SUCCESS)) {

                    Map data = (Map) MapUtils.getObject(jsonMap, DATA);
                    long expiresIn = MapUtils.getLongValue(data, "expiresIn") * 1000;
                    propertie.setProperty("tokenDeathTime", System.currentTimeMillis() + expiresIn + "");
                    propertie.setProperty("companyToken", MapUtils.getString(data, "companyToken"));
                    propertie.setProperty("refreshToken", MapUtils.getString(data, "refreshToken"));
                    System.out.println(MapUtils.getString(data, "companyToken"));
                    propertie.store(pr.getOutputStream(), "刷新授权成功" + new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").format(new Date()));
                } else {
                    log.error("刷新授权失败：jsonMap=" + jsonMap);
                }

            }
        }

    }

    /**
     * 用于下载本地附件文件
     *
     * @param downCode
     * @param response
     * @throws IOException
     */
    @RequestMapping("downLoad")
    public void downLoad(String downCode, HttpServletResponse response) throws IOException {
        String filepATH = map.get(downCode);
        if (StringUtils.isNotBlank(filepATH)) {
            map.remove(downCode);
            try (OutputStream os = response.getOutputStream()) {
                FileUtils.copyFile(new File(filepATH), os);
            }
        }
    }

    /**
     * 档案数据接口：新增档案数据
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("testSaveData")
    public String testSaveData() throws IOException {

        // PathResource pr = new PathResource(new
        // ClassPathResource(PROP_PATH).getURI());
        // Properties propertie = PropertiesLoaderUtils.loadProperties(pr);

        List<Map<String, Object>> dataList = new LinkedList<>();

        Map<String, Object> dataMap = new HashMap<>();

        dataMap.put("groupId", "ws");
        dataMap.put("groupName", "ws");
        dataMap.put("dataId", "1234");

        // 主数据表单：字段和值。可以直接传递第三方的字段名和值对应map，有多少传多少
        Map<String, String> fields = new HashMap<>();
        fields.put("xh", "学号xxx111");
        fields.put("dh", "档号xxx11441");
        fields.put("tm", "题名xxx1177");
        fields.put("nd", "2015");
        dataMap.put("fields", fields);

        List<Map<String,String>> logs = new ArrayList<>();
        Map<String,String> logMap = new HashMap<>();
        logMap.put("userName","张三");
        logMap.put("operateTime","2024-08-11 10:12:11");
        logMap.put("status","通过");
        logMap.put("content","上级领导审批通过，流转到厅领导审批");
        logMap.put("processName","审批");
        logs.add(logMap);
        dataMap.put("processLogs", logs);

        String filepATH = "C:/Users/Administrator/Desktop/文件格式类型.docx";
        String downKey = "aaaaaaabbbbbbb";
        map.put(downKey, filepATH);

        Map<String, String> file = new HashMap<>();
        file.put("name", "文件格式类型.docx");
        file.put("url", ME_PATH + "/ApiTest/downLoad.do?downCode=" + downKey);
        dataMap.put("files", Arrays.asList(file));

        dataList.add(dataMap);

        String appId = "695a0abc616cb3b627e8be954c72c5b595baa33a8cbe3249a129727f15828fae";// propertie.getProperty("appId");
        String companyId = "f222a28a5200d6b13b311c2193af23c7dbf8d2255734f6239531a9b3aeda1d12";// propertie.getProperty("companyId");
        String companyToken = "2981e71ffb49049ee00375d018493e596c2f3c81dd8c45a5c33a3ae61a0f1795";// propertie.getProperty("companyToken");

        // 仅演示用法，实际中Jsoup超时时间很短，如果提交大量数据，并有附件需要档案系统处理，则请设置合理的超时时间
        Connection connection = Jsoup.connect(DARJ_PATH + "/api/data/save").ignoreContentType(true);
        connection = connection.data("appId", appId).data("companyId", companyId).data("companyToken", companyToken);
        String jsonString = JSONArray.toJSONString(dataList);
        connection = connection.data("dataJson", jsonString);
        Map jsonMap = JSON.parseObject(connection.post().text(), Map.class);
        if (MapUtils.getBooleanValue(jsonMap, SUCCESS)) {
            log.error("数据归档成功");
        } else {
            log.error("数据归档失败，失败的数据 ：" + jsonMap);
        }
        return "ok";
    }
}
